import dayjs from 'dayjs'
import type { EntDevices } from '@/api/modules/types/ent'
import type { EditFormData } from '@/views/document/manager/create/create'
import entApi from '@/api/modules/ent'
import { getEntInfo } from '@/utils/dataHook'
import { Electric, Produce, ReusesData } from '@/utils/dataHook/devices'

const useEntStore = defineStore(
  // 唯一ID
  'ent',
  () => {
    const currentEntData = reactive<EntDevices>({
      baseInfo: undefined,
      ElectricDevices: [],
      Produces: {},
      Reuses: {},
      AllReuses: {},
    })
    const currentEntLoading = ref(false)

    function setBaseInfo(data: EditFormData) {
      currentEntData.baseInfo = data
    }
    function setDevices(data: EntDevices) {
      currentEntData.ElectricDevices = data.ElectricDevices
      currentEntData.Produces = data.Produces
      currentEntData.Reuses = data.Reuses
    }
    async function getEntBaseInfo(id: string) {
      const data = await getEntInfo(id)
      data.InstallDate = dayjs(data.InstallDate).format('YYYY-MM-DD')
      currentEntData.baseInfo = data
      return data
    }

    async function refreshDevices(enterpriseObjID: string | undefined) {
      if (!enterpriseObjID) {
        return
      }
      currentEntLoading.value = true
      const res = await entApi.GetProduceReuse({ enterpriseObjID })
      currentEntData.ElectricDevices = res.ElectricDevices.map(item => new Electric(item))
      currentEntData.Produces = Object.entries(res.Produces).reduce((newObj: any, [key, value]) => {
        newObj[key] = new Produce(value)
        return newObj
      }, {})
      currentEntData.Reuses = Object.entries(res.Reuses).reduce((newObj: any, [key, value]) => {
        newObj[key] = new ReusesData(value)
        newObj[key].ReuseParts.forEach((item: any) => {
          currentEntData.AllReuses[item.ObjID] = item
        })
        return newObj
      }, {})
      setTimeout(() => {
        currentEntLoading.value = false
      }, 200)
      return res
    }

    const Produces = computed(() => {
      return Object.keys(currentEntData.Produces).map(key => currentEntData.Produces[key])
    })

    const Reuses = computed(() => {
      return Object.keys(currentEntData.Reuses).map(key => currentEntData.Reuses[key])
    })

    return {
      currentEntLoading,
      currentEntData,
      refreshDevices,
      getEntBaseInfo,
      setBaseInfo,
      setDevices,
      Produces,
      Reuses,
    }
  },
)

export default useEntStore
